package com.chaoyong.higo.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.chaoyong.higo.R;
import com.chaoyong.higo.adapter.LimShopAdapter2;
import com.chaoyong.higo.adapter.LimShopAdapter2.SetHolderListener;
import com.chaoyong.higo.base.BaseActivity;
import com.chaoyong.higo.bean.LimShopBean;
import com.chaoyong.higo.bean.LimShopBean.DataEntity;
import com.chaoyong.higo.utils.V;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.BadgeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class LimitShopActivity extends BaseActivity {

	@Override
	public int layoutResID() {
		return R.layout.activity_limit_shop;
	}

	private Context context;
	private RecyclerView limshop_recyclerview;
	private List<DataEntity> list;
	// private LimShopAdapter adapter;
	private LimShopAdapter2 adapter2;

	private View fuck_layout;

	private BadgeView badgeView;

	// 动画时间
	private int AnimationDuration = 1000;
	// 正在执行的动画数量
	private int number = 0;
	// 是否完成清理
	private boolean isClean = false;
	private FrameLayout animation_viewGroup;
	// 购物车旁标
	// private BadgeView badgeView;
	private Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				// 用来清除动画后留下的垃圾
				try {
					animation_viewGroup.removeAllViews();
				} catch (Exception e) {

				}

				isClean = false;

				break;
			default:
				break;
			}
		}
	};
	private ImageButton base_left_imgbt, base_right_tv;

	@Override
	public void findView() {
		base_left_imgbt = V.f(this, R.id.base_left_imgbt);
		base_right_tv = V.f(this, R.id.base_right_tv);
		limshop_recyclerview = (RecyclerView) findViewById(R.id.limshop_recyclerview);
		fuck_layout = V.f(this, R.id.fuck_layout);
	}

	@Override
	public void init() {
		context = this;
		animation_viewGroup = createAnimLayout();
		base_left_imgbt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		base_right_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, MainActivity.class);
				intent.putExtra("tag", 3);
				context.startActivity(intent);
			}
		});
		list = new ArrayList<DataEntity>();
		LimitShop();

		badgeView = new BadgeView(LimitShopActivity.this, fuck_layout);

		limshop_recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

		adapter2 = new LimShopAdapter2(this);
		setHeader(limshop_recyclerview);
	}

	private void setHeader(RecyclerView view) {
		View header = LayoutInflater.from(this).inflate(R.layout.act_limit_goods_header, view, false);
		adapter2.setHeaderView(header);
	}

	private void doAnim(Drawable drawable, int[] start_location) {
		if (!isClean) {
			setAnim(drawable, start_location);
		} else {
			try {
				animation_viewGroup.removeAllViews();
				isClean = false;
				setAnim(drawable, start_location);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				isClean = true;
			}
		}
	}

	/**
	 * @Description: 创建动画层 @param @return void @throws
	 */
	private FrameLayout createAnimLayout() {
		// ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
		ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
		FrameLayout animLayout = new FrameLayout(context);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;

	}

	/**
	 * @deprecated 将要执行动画的view 添加到动画层
	 * @param vg
	 *            动画运行的层 这里是frameLayout
	 * @param view
	 *            要运行动画的View
	 * @param location
	 *            动画的起始位置
	 * @return
	 */
	private View addViewToAnimLayout(ViewGroup vg, View view, int[] location) {
		int x = location[0];
		int y = location[1];
		vg.addView(view);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(dip2px(context, 90), dip2px(context, 90));
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setPadding(5, 5, 5, 5);
		view.setLayoutParams(lp);

		return view;
	}

	/**
	 * dip，dp转化成px 用来处理不同分辨路的屏幕
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	private int dip2px(Context context, float dpValue) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 动画效果设置
	 * 
	 * @param drawable
	 *            将要加入购物车的商品
	 * @param start_location
	 *            起始位置
	 */
	private void setAnim(Drawable drawable, int[] start_location) {

		Animation mScaleAnimation = new ScaleAnimation(1.5f, 0.0f, 1.5f, 0.0f, Animation.RELATIVE_TO_SELF, 0.1f,
				Animation.RELATIVE_TO_SELF, 0.1f);
		mScaleAnimation.setDuration(AnimationDuration);
		mScaleAnimation.setFillAfter(true);

		final ImageView iview = new ImageView(context);
		iview.setImageDrawable(drawable);
		final View view = addViewToAnimLayout(animation_viewGroup, iview, start_location);
		view.setAlpha(0.6f);

		int[] end_location = new int[2];
		base_right_tv.getLocationInWindow(end_location);
		int endX = end_location[0];
		int endY = end_location[1] - start_location[1];

		Animation mTranslateAnimation = new TranslateAnimation(0, endX, 0, endY);
		Animation mRotateAnimation = new RotateAnimation(0, 180, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		mRotateAnimation.setDuration(AnimationDuration);
		mTranslateAnimation.setDuration(AnimationDuration);
		AnimationSet mAnimationSet = new AnimationSet(true);

		mAnimationSet.setFillAfter(true);
		mAnimationSet.addAnimation(mRotateAnimation);
		mAnimationSet.addAnimation(mScaleAnimation);
		mAnimationSet.addAnimation(mTranslateAnimation);

		mAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub
				number++;
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub

				number--;
				if (number == 0) {
					isClean = true;
					myHandler.sendEmptyMessage(0);
				}

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

		});
		view.startAnimation(mAnimationSet);

	}

	/**
	 * 内存过低时及时处理动画产生的未处理冗余
	 */
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		isClean = true;
		try {
			animation_viewGroup.removeAllViews();
		} catch (Exception e) {
			e.printStackTrace();
		}
		isClean = false;
		super.onLowMemory();
	}

	private void LimitShop() {
		// TODO Auto-generated method stub
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object = new JSONObject();
		try {
			object.put("path", "Home/Goods/limitGood");
			object.put("code", "1");
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		utils.send(HttpMethod.POST, Values.MAIN_RECOMMEND, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				if (result != null) {
					Gson gson = new GsonBuilder().create();
					LimShopBean bean = gson.fromJson(result, new TypeToken<LimShopBean>() {
					}.getType());
					if (bean.getStatus().equals("1")) {
						// list.addAll(bean.getData());
						// adapter = new LimShopAdapter(context, list);
						limshop_recyclerview.setAdapter(adapter2);
						adapter2.addDatas(bean.getData());
						// limshop_recyclerview.setAdapter(adapter);
						adapter2.SetViewHolderListener(new SetHolderListener() {

							@Override
							public void SetOnClinck(Drawable drawable, int[] start_location) {
								doAnim(drawable, start_location);

								badgeView.setBadgeMargin(30, 0);
								badgeView.setBadgeCount(1);
								badgeView.show();
							}
						});
						
					}
				}
			}
		});
	}

	@Override
	public void onClick(View v) {

	}

}
